import redis
from common.settings import logger


class RedisHandler:

    def __init__(self, host: str = '192.168.255.128', port: int = 6379,
                 password: str = '123321', db: int = 0, decode_responses: bool = True):
        self.conn = redis.Redis(host, port, password, db, decode_responses)

    def set_string_data(self, name: str, value: str) -> None:
        try:
            self.conn.set(name, value)
            logger.info(f'添加缓存：{name}')
        except Exception as e:
            logger.error(e)

    def get_string_data(self, name: str) -> str:
        try:
            return self.conn.get(name)
        except Exception as e:
            logger.error(e)

    def set_hash_data(self, name: str, value: dict) -> None:
        try:
            self.conn.hset(name=name, mapping=value)
            logger.info(f'添加缓存：{name}')
        except Exception as e:
            logger.error(e)

    def get_hash_data(self, name: str) -> dict:
        try:
            return self.conn.hgetall(name)
        except Exception as e:
            logger.error(e)

    def is_exists(self, *name: str) -> None:
        try:
            result = self.conn.exists(*name)
            logger.info(f'is_exists: {result}')
        except Exception as e:
            logger.error(e)

    def check_ttl(self, name: str) -> None:
        try:
            result = self.conn.ttl(name)
            logger.info(f'{name} 的有效期：{result}')
        except Exception as e:
            logger.error(e)

    def set_expire(self, name: str, time: int) -> None:
        try:
            self.conn.expire(name, time)
            logger.info(f'设置 {name} 的有效期为 {time} 秒')
        except Exception as e:
            logger.error(e)

    def del_data(self, name: str) -> None:
        try:
            self.conn.delete(name)
            logger.info(f'删除缓存：{name}')
        except Exception as e:
            logger.error(e)


if __name__ == '__main__':
    redis_handler = RedisHandler()
    redis_handler.set_hash_data('res1', {'name': '李四', 'age': 30})
    redis_handler.get_hash_data('res1')
    redis_handler.check_ttl('res1')
    redis_handler.set_expire('res1', 10)
    redis_handler.check_ttl('res1')
    redis_handler.del_data('res1')
    redis_handler.is_exists('res1')
